package com.power.using.mytoutiao.ui;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentTransaction;

import com.getkeepsafe.taptargetview.TapTarget;
import com.getkeepsafe.taptargetview.TapTargetSequence;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.power.using.mytoutiao.R;
import com.power.using.mytoutiao.module.base.BaseActivity;
import com.power.using.mytoutiao.module.news.NewsTabLayout;
import com.power.using.mytoutiao.util.SettingUtil;
import com.power.using.mytoutiao.widget.helper.BottomNavigationViewHelper;

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar toolbar;
    private BottomNavigationView bottom_navigation;
    private DrawerLayout drawer_layout;
    private NavigationView nav_view;

    private static final String POSITION = "position";
    private static final String SELECT_ITEM = "bottomNavigationSelectItem";

    private static final int FRAGMENT_NEWS = 0;
    private static final int FRAGMENT_PHOTO = 1;
    private static final int FRAGMENT_VIDEO = 2;
    private static final int FRAGMENT_MEDIA = 3;
    private long exitTime;
    private NewsTabLayout newsTabLayout;
    private NewsTabLayout photoTabLayout;
    private NewsTabLayout videoTabLayout;
    private NewsTabLayout mediaTabLayout;

    private int position;
    private long firstClickTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        if(savedInstanceState!=null){
            newsTabLayout = (NewsTabLayout) getSupportFragmentManager().findFragmentByTag(NewsTabLayout.class.getName());
            photoTabLayout = (NewsTabLayout) getSupportFragmentManager().findFragmentByTag(NewsTabLayout.class.getName());
            videoTabLayout = (NewsTabLayout) getSupportFragmentManager().findFragmentByTag(NewsTabLayout.class.getName());
            mediaTabLayout = (NewsTabLayout) getSupportFragmentManager().findFragmentByTag(NewsTabLayout.class.getName());

            showFragment(savedInstanceState.getInt(POSITION));
            bottom_navigation.setSelectedItemId(savedInstanceState.getInt(SELECT_ITEM));
        }else{
            showFragment(FRAGMENT_NEWS);
        }

        if(SettingUtil.getInstance().getIsFirstTime()){
            showTapTarget();
        }
    }

    private void showTapTarget() {

        final Display display = getWindowManager().getDefaultDisplay();
        final Rect target = new Rect(
                0,
                display.getHeight(),
                0,
                display.getHeight());
        target.offset(display.getWidth() / 8, -56);

        TapTargetSequence sequence=new TapTargetSequence(this)
                .targets(
                        TapTarget.forToolbarMenuItem(toolbar, R.id.action_search, "点击这里进行搜索")
                                .dimColor(android.R.color.black)
                                .outerCircleColor(R.color.colorPrimary)
                                .drawShadow(true)
                                .id(1),
                        TapTarget.forToolbarNavigationIcon(toolbar, "点击这里展开侧栏")
                                .dimColor(android.R.color.black)
                                .outerCircleColor(R.color.colorPrimary)
                                .drawShadow(true)
                                .id(2),
                        TapTarget.forBounds(target, "点击这里切换新闻", "双击返回顶部\n再次双击刷新当前页面")
                                .dimColor(android.R.color.black)
                                .outerCircleColor(R.color.colorPrimary)
                                .targetRadius(60)
                                .transparentTarget(true)
                                .drawShadow(true)
                                .id(3)
                ).listener(new TapTargetSequence.Listener() {
                    @Override
                    public void onSequenceFinish() {
                        SettingUtil.getInstance().setIsFirstTime(false);
                    }

                    @Override
                    public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) {

                    }

                    @Override
                    public void onSequenceCanceled(TapTarget lastTarget) {
                        SettingUtil.getInstance().setIsFirstTime(false);
                    }
                });

        sequence.start();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(POSITION,position);
        outState.putInt(SELECT_ITEM,bottom_navigation.getSelectedItemId());
    }

    private void initView() {
        toolbar=findViewById(R.id.toolbar);
        toolbar.inflateMenu(R.menu.menu_activity_main);
        bottom_navigation = findViewById(R.id.bottom_navigation);
        BottomNavigationViewHelper.disableShiftMode(bottom_navigation);
        setSupportActionBar(toolbar);
        bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                switch(menuItem.getItemId()){
                    case R.id.action_news:
                        showFragment(FRAGMENT_NEWS);
                        doubClick(FRAGMENT_NEWS);
                        break;
                    case R.id.action_photo:
                        showFragment(FRAGMENT_PHOTO);
                        doubClick(FRAGMENT_PHOTO);
                        break;
                    case R.id.action_video:
                        showFragment(FRAGMENT_VIDEO);
                        doubClick(FRAGMENT_VIDEO);
                        break;
                    case R.id.action_media:
                        showFragment(FRAGMENT_MEDIA);
                        break;
                }
                return true;
            }
        });
        drawer_layout = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer_layout.addDrawerListener(toggle);
        toggle.syncState();

        nav_view = findViewById(R.id.nav_view);
        nav_view.setNavigationItemSelectedListener(this);

    }

    public void doubClick(int index) {
        long secondClickTime = System.currentTimeMillis();

        if((secondClickTime-firstClickTime)<500){
            switch(index){
                case FRAGMENT_NEWS:
                    newsTabLayout.onDoubleClick();
                    break;

                case FRAGMENT_PHOTO:
                    photoTabLayout.onDoubleClick();
                    break;

                case FRAGMENT_VIDEO:
                    videoTabLayout.onDoubleClick();
                    break;
            }
        }else{
            firstClickTime = secondClickTime;
        }

    }

    public void showFragment(int index) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        hideFragment(ft);
        position=index;
        switch(index){
            case FRAGMENT_NEWS:
                toolbar.setTitle(R.string.app_name);

                if(newsTabLayout==null){
                    newsTabLayout=NewsTabLayout.getInstance();
                    ft.add(R.id.container,newsTabLayout,NewsTabLayout.class.getName());
                }else{
                    ft.show(newsTabLayout);
                }
                break;

            case FRAGMENT_PHOTO:

                toolbar.setTitle(R.string.title_photo);

                if(photoTabLayout==null){
                    photoTabLayout=NewsTabLayout.getInstance();
                    ft.add(R.id.container,photoTabLayout,NewsTabLayout.class.getName());
                }else{
                    ft.show(photoTabLayout);
                }


                break;

            case FRAGMENT_VIDEO:
                toolbar.setTitle(getString(R.string.title_video));
                if (videoTabLayout == null) {
                    videoTabLayout = NewsTabLayout.getInstance();
                    ft.add(R.id.container, videoTabLayout, NewsTabLayout.class.getName());
                } else {
                    ft.show(videoTabLayout);
                }
                break;

            case FRAGMENT_MEDIA:
                toolbar.setTitle(getString(R.string.title_media));
                if (mediaTabLayout == null) {
                    mediaTabLayout = NewsTabLayout.getInstance();
                    ft.add(R.id.container, mediaTabLayout, NewsTabLayout.class.getName());
                } else {
                    ft.show(mediaTabLayout);
                }
                break;
        }


        ft.commit();

    }


    private void hideFragment(FragmentTransaction ft) {

        if(newsTabLayout!=null){
            ft.hide(newsTabLayout);
        }

        if(photoTabLayout!=null){
            ft.hide(photoTabLayout);
        }

        if(videoTabLayout!=null){
            ft.hide(videoTabLayout);
        }

        if(mediaTabLayout!=null){
            ft.hide(mediaTabLayout);
        }


    }

    @Override
    public void onBackPressed() {

        long currentTime=System.currentTimeMillis();
        if((currentTime-exitTime)<2000){
            super.onBackPressed();
        }else{
            Toast.makeText(MainActivity.this, R.string.double_click_exit, Toast.LENGTH_SHORT).show();
            exitTime = currentTime;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_activity_main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId()==R.id.action_search){

        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        int id = item.getItemId();
        switch(id){
            case R.id.nav_switch_night_mode:
                int mode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
                if (mode == Configuration.UI_MODE_NIGHT_YES) {
                    SettingUtil.getInstance().setIsNightMode(false);
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                } else {
                    SettingUtil.getInstance().setIsNightMode(true);
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                }
                getWindow().setWindowAnimations(R.style.WindowAnimationFadeInOut);
                recreate();
                return false;

            case R.id.nav_setting:
                //startActivity(new Intent(this, SettingActivity.class));
                drawer_layout.closeDrawers();
                return false;

            case R.id.nav_share:
                Intent shareIntent = new Intent()
                        .setAction(Intent.ACTION_SEND)
                        .setType("text/plain")
                        .putExtra(Intent.EXTRA_TEXT, getString(R.string.share_app_text) + getString(R.string.source_code_url));
                startActivity(Intent.createChooser(shareIntent, getString(R.string.share_to)));
                drawer_layout.closeDrawers();
                return false;
        }


        return false;

    }

}
